package br.com.sendmail.operacoes;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import br.com.sendmail.modelo.ContaEmail;
import br.com.sendmail.util.LoadDadosXML;

/**
 * 29/11/2012 - CarregarContas.java 
 * Elton Souza - eltonds88@gmail.com
 * 
 * Classe que carrega as contas do arquivo de configuracao.
 * O nome do arquivo deve ser send-mail.xml e deve se encontrar na pasta WEB-INF
 * 
 * Metodos privados ou pretected para garantir que somente a classe SendMail a utilize.
 */
public final class Contas extends LoadDadosXML implements Serializable {

	private static final long serialVersionUID = 1L;

	private static List<ContaEmail> contas;

	protected Contas(ServletContext context) {
		if(contas == null) {
			this.carregarContas(context);
		}
	}

	private void carregarContas(ServletContext context) {
		try {
			Document doc = super.getArquivo(context.getRealPath(SendMail.ARQUIVO_CONF));
			if(doc != null) {
				contas = new ArrayList<ContaEmail>();
				NodeList nl = doc.getElementsByTagName(ContaEmail.XML_ELEMENT_NAME);
				if(nl != null && nl.getLength() > 0) {
					for(int i = 0 ; i < nl.getLength();i++) {
						Element email = (Element)nl.item(i);
						contas.add(this.getContaEmail(email));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ContaEmail getContaEmail(Element email) throws Exception {
		String porta = super.getValue(email, 0, "porta");
		if(porta==null) {
			porta = ContaEmail.PORT_NUMBER;
		}
		boolean debug = "true".equalsIgnoreCase(super.getValue(email, 0, "debug"));
		return new ContaEmail(super.getValue(email, 0, "nomeConta"), super.getValue(email, 0, "host"), 
				super.getValue(email, 0, "authMail"), super.getValue(email, 0, "authPassw"), 
				super.getValue(email, 0, "fromEmail"), super.getValue(email, 0, "fromName"), 
				super.getValue(email, 0, "copyTo"), porta, super.getValue(email, 0, "localhost"), debug);
	}

	protected static synchronized ContaEmail getConta(String nomeConta) {
		ContaEmail conta = null;
		if(contas != null) {
			for(ContaEmail c : contas) {
				if(c.getNomeConta().equals(nomeConta)) {
					conta = c;
					break;
				}
			}
		}
		return conta;
	}

}
